<template>
  <div class="dashboard-container">
    <!-- 操作栏 -->
    <div class="action-bar">
      <el-button size="small" @click="goToHome">返回主页</el-button>
      <el-input
        v-model="searchKeyword"
        placeholder="搜索职位"
        clearable
        @clear="fetchJobs"
        @keyup.enter="fetchJobs"
        class="search-input"
      ></el-input>
    </div>

    <!-- 职位列表 -->
    <div class="job-grid">
      <el-card
        v-for="job in filteredJobs"
        :key="job.job_id"
        class="job-card"
        shadow="hover"
      >
        <template #header>
          <div class="card-header">
            <span class="job-title">{{ job.job_title }}</span>
          </div>
        </template>
        <div class="card-content">
          <p><strong>公司名称:</strong> {{ job.company_name }}</p>
          <p><strong>工作地点:</strong> {{ job.location }}</p>
          <p><strong>薪资范围:</strong> {{ job.salary_range || '面议' }}</p>
          <p><strong>职位状态:</strong>
            <el-tag :type="job.is_open ? 'success' : 'info'">
              {{ job.is_open ? '招聘中' : '已结束' }}
            </el-tag>
          </p>
          <p class="update-time">发布时间: {{ formatDate(job.post_date) }}</p>
        </div>
        <div class="card-actions">
          <el-button type="primary" size="small" @click="applyJob(job.job_id)">投递</el-button>
          <el-button type="info" size="small" @click="openMessageDialog(job)">发消息</el-button>
        </div>
      </el-card>
    </div>

    <!-- 发消息弹窗 -->
    <el-dialog title="给发布者发消息" v-model="messageDialogVisible" width="40%">
      <el-form :model="messageForm" label-width="100px">
        <el-form-item label="消息内容" required>
          <el-input type="textarea" rows="4" v-model="messageForm.content" placeholder="请输入消息"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="messageDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="loading" @click="sendMessage">发送</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '../store/auth'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()
const auth = useAuthStore()
const loading = ref(false)

const searchKeyword = ref('')
const jobs = ref([])

// 消息对话框
const messageDialogVisible = ref(false)
const messageForm = ref({ content: '' })
let targetJob = null

// 登录检查与获取职位
const fetchJobs = async () => {
  if (!auth.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  loading.value = true
  try {
    const token = auth.token
    const res = await fetch('http://127.0.0.1:8000/api/job-postings?is_open=true', {
      headers: { 'Authorization': `Bearer ${encodeURIComponent(token)}` }
    })
    if (!res.ok) throw new Error(await res.text())
    jobs.value = await res.json()
  } catch (err) {
    ElMessage.error('获取职位失败: ' + err.message)
  } finally {
    loading.value = false
  }
}

const filteredJobs = computed(() => {
  if (!searchKeyword.value) return jobs.value
  return jobs.value.filter(j => j.job_title.includes(searchKeyword.value))
})

// 投递职位
const applyJob = async (jobId) => {
  if (!auth.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  try {
    loading.value = true
    const token = auth.token
    const res = await fetch(`http://127.0.0.1:8000/api/applications?applicant_id=${auth.userId}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${encodeURIComponent(token)}`
      },
      body: JSON.stringify({ job_id: jobId, cover_letter: '' })
    })
    if (!res.ok) throw new Error(await res.text())
    ElMessage.success('投递成功')
  } catch (err) {
    ElMessage.error('投递失败: ' + err.message)
  } finally {
    loading.value = false
  }
}

// 打开发消息对话框
const openMessageDialog = (job) => {
  targetJob = job
  messageForm.value.content = ''
  messageDialogVisible.value = true
}

// 发送消息
const sendMessage = async () => {
  if (!messageForm.value.content) {
    ElMessage.warning('请输入消息内容')
    return
  }
  try {
    loading.value = true
    const token = auth.token
    const res = await fetch(`http://127.0.0.1:8000/api/messages?sender_id=${auth.userId}&receiver_id=${targetJob.user_id}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${encodeURIComponent(token)}`
      },
      body: JSON.stringify({
        receiver_id: targetJob.user_id,
        related_job_id: targetJob.job_id,
        content: messageForm.value.content
      })
    })
    if (!res.ok) throw new Error(await res.text())
    ElMessage.success('消息发送成功')
    messageDialogVisible.value = false
  } catch (err) {
    ElMessage.error('发送失败: ' + err.message)
  } finally {
    loading.value = false
  }
}

const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 返回主页
const goToHome = () => {
  router.push('/')
}

onMounted(fetchJobs)
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}
.action-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}
.search-input {
  width: 300px;
}
.job-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
}
.job-card {
  border-radius: 8px;
}
.card-header {
  font-size: 18px;
  font-weight: bold;
}
.card-content {
  padding: 10px;
}
.update-time {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
}
.card-actions {
  padding: 10px;
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}
</style>